package logic

import (
	"context"
	"strconv"
	"zhihu/pkg"
	"zhihu/zhihurpc/zhihurpcclient"

	"zhihu/api/internal/svc"
	"zhihu/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterOrLoginUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterOrLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterOrLoginUserLogic {
	return &RegisterOrLoginUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterOrLoginUserLogic) RegisterOrLoginUser(req *types.RegisterOrLoginUserRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	registerOrLogin, err := l.svcCtx.ZhiHuRpc.RegisterOrLoginUser(l.ctx, &zhihurpcclient.RegisterOrLoginUserRequest{
		Mobile:  req.Mobile,
		CodeSms: req.CodeSms,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Data:    nil,
			Code:    500,
		}, nil
	}

	handler, err := pkg.TokenHandler(strconv.FormatInt(registerOrLogin.UserId, 10))
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Data:    nil,
			Code:    500,
		}, nil
	}

	return &types.Response{
		Message: "登录成功",
		Data:    handler,
		Code:    200,
	}, nil
}
